<template>
  <div class="user_page">
    <div class="user_search">
      <el-button type="primary" icon="el-icon-edit" size="small" @click.stop="handleCreate">添加用户</el-button>
      <el-input v-model="cdtUsername" placeholder="账号" size="small" clearable style="width: 180px"></el-input>
      <el-input v-model="cdtSname" placeholder="门店" size="small" clearable style="width: 180px"></el-input>
      <el-button type="primary" icon="el-icon-search" size="small" :disabled="listLoading" @click.stop="loadUserList">
        查询
      </el-button>
      <el-button icon="el-icon-refresh" size="small" @click.stop="resetSearch">重置</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column
        fixed
        prop="username"
        label="账号"
        align="left"
        width="150"
        show-overflow-tooltip></el-table-column>
      <el-table-column
        fixed
        prop="nickName"
        label="用户名"
        align="left"
        width="150"
        show-overflow-tooltip></el-table-column>
      <el-table-column
        prop="deptId"
        label="角色"
        align="left"
        width="150"
        show-overflow-tooltip
        :formatter="fmtRole"></el-table-column>
      <el-table-column prop="sname" label="所属门店" align="center" width="500" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="380">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" plain @click="handleUpdate(row)">编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            plain
            :disabled="row.username == 'admin'"
            @click="handleDelete(row.id, $index)">
            删除
          </el-button>
          <el-button type="primary" size="mini" plain @click="handlePwd(row.username)">改密</el-button>
          <el-button v-if="row.isFrozen === 0" type="danger" size="mini" plain @click="frozeUser(row, 1)">
            停用
          </el-button>
          <el-button v-else type="success" size="mini" plain @click="frozeUser(row, 0)">启用</el-button>
          <el-button type="warning" size="mini" plain @click="logoutUser(row.username)">登出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="loadUserList"></pagination>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="adminObj" label-width="110px" :rules="rules" size="small">
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="adminObj.username"
            :disabled="!isAdd"
            maxlength="21"
            show-word-limit
            clearable
            style="width: 380px"></el-input>
        </el-form-item>
        <el-form-item v-show="isAdd" label="密码" prop="note">
          <el-input v-model="adminObj.note" maxlength="21" show-word-limit clearable style="width: 380px"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="nickName">
          <el-input
            v-model="adminObj.nickName"
            maxlength="32"
            show-word-limit
            clearable
            style="width: 380px"></el-input>
        </el-form-item>
        <el-form-item label="角色" required>
          <span v-if="adminObj.username == 'admin'">超级理员</span>
          <el-select
            v-else
            v-model="adminObj.deptId"
            placeholder="请选择角色"
            clearable
            :disabled="!isAdmin"
            style="width: 200px">
            <el-option v-for="item in sysRoles" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isNeedRegion() || isNeedSalon()" :label="isNeedSalon() ? '城市和门店' : '所属城市'">
          <region-select
            ref="refRegionSelect"
            :mode="isNeedSalon() ? 2 : 1"
            :dept="2"
            @change="handleRegionChange"
            @selected="handleSalonSelected"></region-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click.stop="handleSubmitUser()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { changeFrozen, changePwd, delAdmin, editAdmin, getUserPage, logoutById, register } from '@/api/admin';
import { addAdminScore } from '@/api/ym';
import { getRoleName, isAdminRole, isRoleNeedRegion, isRoleNeedSalon, systemRoles } from '@/utils/enum/roles';
// 引入自定义组件
import Pagination from '@/components/Pagination';
import RegionSelect from '@/views/salon/RegionSelect.vue';
// 引入第三方组件
import dayjs from 'dayjs';
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

export default {
  components: { Pagination, ['region-select']: RegionSelect },
  filters: {
    parseTime(time) {
      return dayjs(time).format('YYYY-MM-DD');
    },
  },
  data() {
    return {
      cdtUsername: '',
      cdtSname: '',
      title: '',
      isAdd: false,
      list: [],
      listLoading: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 12,
      },
      sysRoles: [],
      dialogFormVisible: false,
      adminObj: {
        id: undefined,
        username: '',
        note: '',
        nickName: '',
        deptId: 203,
        openId: '0',
        sname: '',
        regionCode: null,
        regionPaths: null,
      },
      rules: {
        username: [{ required: true, message: '必填项', trigger: 'blur' }],
        note: [{ required: true, message: '必填项', trigger: 'blur' }],
        nickName: [{ required: true, message: '必填项', trigger: 'blur' }],
      },
    };
  },
  computed: {
    ...mapGetters(['name', 'id', 'deptId', 'openId']),
    isAdmin() {
      return isAdminRole(this.deptId);
    },
  },
  created() {
    if (this.name == 'admin') {
      this.sysRoles = systemRoles;
    } else {
      this.sysRoles = systemRoles.filter(x => x.id != 1);
    }
    this.loadUserList();
  },
  methods: {
    logoutUser(un) {
      logoutById(un).then(_ => {
        this.$notify({
          title: '成功',
          message: '退出登录',
          type: 'success',
          duration: 1000,
        });
      });
    },
    isNeedRegion() {
      return isRoleNeedRegion(this.adminObj.deptId);
    },
    isNeedSalon() {
      return isRoleNeedSalon(this.adminObj.deptId);
    },
    resetSearch() {
      this.cdtSname = '';
      this.cdtUsername = '';
      this.loadUserList();
    },
    frozeUser(row, froze) {
      row.isFrozen = froze;
      const dataInfo = new FormData();
      dataInfo.append('froze', froze);
      changeFrozen(row.id, dataInfo);
    },
    fmtRole(row) {
      const tmp = getRoleName(row.deptId);
      return tmp === undefined ? '' : tmp;
    },
    loadUserList: async function () {
      if (this.listLoading) {
        return;
      }
      this.listLoading = true;
      const errAlertMsg = '查询用户列表失败';
      const params = { pageNumber: this.listQuery.page, pageSize: this.listQuery.limit };
      if (this.cdtUsername) {
        params.username = this.cdtUsername;
      }
      if (this.cdtSname) {
        params.sname = this.cdtSname;
      }
      this.list.splice(0, this.list.length);
      await getUserPage(params)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            if (ret.records && ret.records.length) {
              this.list.push(...ret.records);
            }
            this.total = ret.total;
          }
        })
        .catch(err => {
          console.error(err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => (this.listLoading = false));
    },
    handleRegionChange: async function (rg) {
      if (rg) {
        this.adminObj.regionCode = rg.regionCode;
        if (this.adminObj.regionPaths) {
          this.adminObj.regionPaths.splice(0, this.adminObj.regionPaths.length);
          this.adminObj.regionPaths.push(rg.regionPath);
        } else {
          this.adminObj.regionPaths = [];
          this.adminObj.regionPaths.push(rg.regionPath);
        }
      }
    },
    handleSalonSelected: async function (salon) {
      if (salon) {
        this.adminObj.openId = salon.salonId;
        this.adminObj.sname = salon.salonName;
      }
    },
    handleCreate: async function () {
      this.title = '新增';
      this.isAdd = true;
      this.adminObj.username = '';
      this.adminObj.nickName = '';
      this.dialogFormVisible = true;
      await this.$nextTick();
      this.$refs['dataForm'].clearValidate();
    },
    handleUpdate: async function (row) {
      this.title = '编辑';
      this.isAdd = false;
      this.dialogFormVisible = true;
      this.adminObj = Object.assign({}, row);
      await this.$nextTick();
      this.$refs['dataForm'].clearValidate();
      if (row.regionPaths && row.regionPaths.length) {
        this.$refs.refRegionSelect.setRegionPath(row.regionPaths[0]);
      }
      if (row.openId && this.$refs.refRegionSelect) {
        this.$refs.refRegionSelect.setSalonId(row.openId);
      }
    },
    handleSubmitUser() {
      if (this.isNeedRegion()) {
        if (!this.adminObj.regionPaths || !this.adminObj.regionPaths.length) {
          MessageBox.alert('请选择城市');
          return;
        }
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.adminObj);
          if (this.isAdd) {
            this.doAddUser(tempData);
          } else if (!this.isAdd) {
            this.doMdfUser(tempData);
          }
        }
      });
    },
    doAddUser: async function (tempData) {
      const errAlertMsg = '添加用户出错';
      await register(tempData)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const d = res.data.data;
          this.list.unshift(d);
          // 为新用户生成积分
          if (d.deptId > 201) {
            addAdminScore({
              uid: d.id,
              uname: d.nickName,
              duties: d.deptId,
              score: 100,
              sid: d.openId,
              sname: d.sname,
            });
          }
          this.dialogFormVisible = false;
          this.$notify({
            title: res.data.message,
            message: res.data.status,
            type: 'success',
            duration: 2000,
          });
        })
        .catch(err => {
          console.error(err);
          MessageBox.alert(errAlertMsg);
        });
    },
    doMdfUser: async function (tempData) {
      const errAlertMsg = '更新用户出错';
      editAdmin(tempData)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const index = this.list.findIndex(v => v.id === this.adminObj.id);
          this.list.splice(index, 1, tempData);
          this.dialogFormVisible = false;
          this.$message({ type: 'success', message: '更新成功' });
        })
        .catch(err => {
          console.error(err);
          MessageBox.alert(errAlertMsg);
        });
    },
    handleDelete(id, index) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delAdmin(id).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000,
            });
          });
          this.list.splice(index, 1);
        })
        .catch(() => {});
    },
    handlePwd(username) {
      this.$prompt('请输入新密码', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '请输入密码',
      }).then(({ value }) => {
        changePwd({ password: value, username })
          .then(() => {
            this.$message({
              type: 'success',
              message: '密码修改成功',
            });
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '密码修改失败，请稍后再试',
            });
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/scrollbar.scss';

.user_page {
  width: 100%;

  .user_search {
    padding: 5px 16px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    gap: 5px;
  }
}

::v-deep .el-table td {
  padding: 5px 0;
  min-width: 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
}
</style>
